<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.wan888888.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use Admin\Model\CommentModel;
use Admin\Model\MedicalCommentModel;
use Admin\Model\RecordModel;
use Admin\Model\UserModel;
use Api\Model\MedicalRecordModel;
use Common\Service\WeChatService;
use Think\Log;
use Common\Util\ConfigUtils;

/**
 * 病历控制器
 * @author xu
 */
class RecordController extends AdminController {

    /**
     * 病历列表
     * @author xu
     */
    public function index(){
        $name       =   I('name');
        $hospital   =   I('hospital');
        $where['r.is_show']  =   array('eq',1);
        $name && $where['u.name']    =   array('like', '%'.(string)$name.'%');
        $hospital && $where['u.hospital']    =   array('like', '%'.(string)$hospital.'%');

        $yanya_start    =   I('yanya_start');
        $yanya_end      =   I('yanya_end');
        $jiaomo_start   =   I('jiaomo_start');
        $jiaomo_end     =   I('jiaomo_end');
        $bodian_start   =   I('bodian_start');
        $bodian_end     =   I('bodian_end');
        $qulv_start     =   I('qulv_start');
        $qulv_end       =   I('qulv_end');

        if($yanya_start ||$yanya_end ||$jiaomo_start||$jiaomo_end||$bodian_start ||$bodian_end ||$qulv_start||$qulv_end){
            $where1=[];
            $where2=[];
            if($yanya_start){
                $where1['l_intraocular_pressure'][]=array('egt',$yanya_start);
                $where2['r_intraocular_pressure'][]=array('egt',$yanya_start);

            }
            if($yanya_end){
                $where1['l_intraocular_pressure'][]=array('elt',$yanya_end);
                $where2['r_intraocular_pressure'][]=array('elt',$yanya_end);
            }
            if($jiaomo_start){
                $where1['l_corneal_diameter'][]=array('egt',$jiaomo_start);
                $where2['r_corneal_diameter'][]=array('egt',$jiaomo_start);

            }
            if($jiaomo_end){
                $where1['l_corneal_diameter'][]=array('elt',$jiaomo_end);
                $where2['r_corneal_diameter'][]=array('elt',$jiaomo_end);

            }
            if($bodian_start){
                $where1['l_thin_thickness'][]=array('egt',$bodian_start);
                $where2['r_thin_thickness'][]=array('egt',$bodian_start);

            }
            if($bodian_end){
                $where1['l_thin_thickness'][]=array('elt',$bodian_end);
                $where2['r_thin_thickness'][]=array('elt',$bodian_end);

            }
            if($qulv_start){
                $where1['l_max_curvature'][]=array('egt',$qulv_start);
                $where2['r_max_curvature'][]=array('egt',$qulv_start);

            }
            if($qulv_end){
                $where1['l_max_curvature'][]=array('elt',$qulv_end);
                $where2['r_max_curvature'][]=array('elt',$qulv_end);

            }
            $where['_complex'] = array(
                $where1,
                $where2,
                '_logic' => 'or'
            );
        }


        $total =RecordModel::singleton()->getCount($where);
        $limit = $this->pagination($total);
        $list = RecordModel::singleton()->getList($where,$limit);
        $marriageArr=array(
            0=>'未婚',
            1=>'已婚'
        );
        int_to_string($list);
        foreach($list as $k=>$v){
            $list[$k]['marriage_status']=$marriageArr[$v['marriage_status']];
        }
        $this->assign('_list', $list);
        $this->display();
    }


    public function export(){
        $type = I('type');

        $ids = I('ids');
        $where['r.is_show']  =   array('eq',1);
        if ($type === 'CHECKED') {
            $where = ['r.id' => ['in', explode(',',$ids)]];
        } else if ($type === 'FILTERED' ) {
            $name       =   I('name');
            $hospital   =   I('hospital');
            $name && $where['u.name']    =   array('like', '%'.(string)$name.'%');
            $hospital && $where['u.hospital']    =   array('like', '%'.(string)$hospital.'%');
            $yanya_start    =   I('yanya_start');
            $yanya_end      =   I('yanya_end');
            $jiaomo_start   =   I('jiaomo_start');
            $jiaomo_end     =   I('jiaomo_end');
            $bodian_start   =   I('bodian_start');
            $bodian_end     =   I('bodian_end');
            $qulv_start     =   I('qulv_start');
            $qulv_end       =   I('qulv_end');

            if($yanya_start ||$yanya_end ||$jiaomo_start||$jiaomo_end||$bodian_start ||$bodian_end ||$qulv_start||$qulv_end){
                $where1=[];
                $where2=[];
                if($yanya_start){
                    $where1['l_intraocular_pressure'][]=array('egt',$yanya_start);
                    $where2['r_intraocular_pressure'][]=array('egt',$yanya_start);

                }
                if($yanya_end){
                    $where1['l_intraocular_pressure'][]=array('elt',$yanya_end);
                    $where2['r_intraocular_pressure'][]=array('elt',$yanya_end);
                }
                if($jiaomo_start){
                    $where1['l_corneal_diameter'][]=array('egt',$jiaomo_start);
                    $where2['r_corneal_diameter'][]=array('egt',$jiaomo_start);

                }
                if($jiaomo_end){
                    $where1['l_corneal_diameter'][]=array('elt',$jiaomo_end);
                    $where2['r_corneal_diameter'][]=array('elt',$jiaomo_end);

                }
                if($bodian_start){
                    $where1['l_thin_thickness'][]=array('egt',$bodian_start);
                    $where2['r_thin_thickness'][]=array('egt',$bodian_start);

                }
                if($bodian_end){
                    $where1['l_thin_thickness'][]=array('elt',$bodian_end);
                    $where2['r_thin_thickness'][]=array('elt',$bodian_end);

                }
                if($qulv_start){
                    $where1['l_max_curvature'][]=array('egt',$qulv_start);
                    $where2['r_max_curvature'][]=array('egt',$qulv_start);

                }
                if($qulv_end){
                    $where1['l_max_curvature'][]=array('elt',$qulv_end);
                    $where2['r_max_curvature'][]=array('elt',$qulv_end);

                }
                $where['_complex'] = array(
                    $where1,
                    $where2,
                    '_logic' => 'or'
                );
            }
        }

        $list =  RecordModel::singleton()->alias('r')
            ->join('__TB_MD_USER__ u on r.user_id = u.id','Left')
            ->join('__TB_MD_MEDICAL_RECORD_DETAIL__ rd on r.id = rd.record_id','Left')
            ->where($where)
            ->field('r.*,rd.*,r.id as rid,u.name doctor_name,u.hospital')
            ->order("r.create_time desc")
            ->select()?:[];


        $recordIdsCell =array();
        $excelNum = 0;
        foreach($list as $key=>$val){
            $recordIdsCell[$val['rid']][]=$excelNum;
            $list[$key]['index']=$key+1;
            $list[$key]['marriage_status']=$val['marriage_status']==1?"已婚":"未婚";
            $list[$key]['wear_status']=$val['wear_glasses']==1?"是；"."戴".$val['wear_year']."年,停戴".$val['stop_wear_week']."周。":"否；"."戴".$val['wear_year']."年,停戴".$val['stop_wear_week']."周。";
            $list[$key]['eyelid_status']=implode(',',unserialize($val['eyelid_status']));
            $list[$key]['past_history']=implode(',',unserialize($val['past_history']));
            if($val['id']){
                $list[$key]['url']="https://project.wan888888.com/dmk_bj/index.php?s=/Admin/Record/detail&id=".$val['id'];
            }else{
                $list[$key]['url']="";
            }

            $excelNum++;
        }

        //获取需要excel合并的行数
        foreach($recordIdsCell as $k=>$v){
            if(count($v) == 1) unset($recordIdsCell[$k]);
        }




        $excelList = $list;
        //导出excel
        $fieldlist = array(
            "序号","姓名","系统id","年龄","婚姻","性别","籍贯","职业","是否配戴隐形眼镜","近视时长","配镜时长",
            "现镜OD","现镜OS","2年内屈光度变化","眼睑状况","既往史及家族史","患者诉求","处理结果","病例图片链接","检查时间",
            "显然验光DS","显然验光DC","显然验光°","显然验光4","散瞳验光DS","散瞳验光DC","散瞳验光°","散瞳验光4","眼压","角膜横径","最薄点厚度","最大曲率",
            "显然验光DS","显然验光DC","显然验光°","显然验光4","散瞳验光DS","散瞳验光DC","散瞳验光°","散瞳验光4","眼压","角膜横径","最薄点厚度","最大曲率"
        );

        $field_list= array(
            "index","name","id_number","age","marriage_status","sex","native_place","occupation","wear_status","myopia_year","optician_year",
            "mirror_od","mirror_os","diopte_change","eyelid_status","past_history","patient_appeall","processing_results","url","check_time",
            "r_apparent_optometry_ds","r_apparent_optometry_dc","r_apparent_optometry_degree","r_apparent_optometry_equals","r_cycloplegic_refraction_ds","r_cycloplegic_refraction_dc","r_cycloplegic_refraction_degree","r_cycloplegic_refraction_equals","r_intraocular_pressure","r_corneal_diameter","r_thin_thickness","r_max_curvature",
            "l_apparent_optometry_ds","l_apparent_optometry_dc","l_apparent_optometry_degree","l_apparent_optometry_equals","l_cycloplegic_refraction_ds","l_cycloplegic_refraction_dc","l_cycloplegic_refraction_degree","l_cycloplegic_refraction_equals","l_intraocular_pressure","l_corneal_diameter","l_thin_thickness","l_max_curvature",
        );

        $caselist = array();
        for($i='A';$i<='Z';$i++){
            $caselist[]=$i;
        }

        $sheetWidth = array(
            "A"=>10,"B"=>15,"C"=>20,"D"=>10,"E"=>20,"F"=>20,"G"=>20, "H"=>20,"I"=>20,
            "J"=>20,"K"=>30,"L"=>20,"M"=>20,"N"=>20, "O"=>20,"P"=>20,"Q"=>20,"R"=>30,
            "S"=>80,"T"=>20,"U"=>20, "V"=>20,"W"=>20,"X"=>20,"Y"=>30,"Z"=>20,"AA"=>20,
            "AB"=>20,"AC"=>20,"AD"=>30,"AE"=>20,"AF"=>20,"AG"=>20, "AH"=>20,"AI"=>20,
            "AJ"=>20, "AK"=>30,"AL"=>20,"AM"=>20,"AN"=>20, "AO"=>20,"AP"=>20,"AQ"=>20,
            "AR"=>30,
        );


        ini_set('memory_limit', '1024M');

        require_once __DIR__ . '/../../../ThinkPHP/Library/Vendor/PHPExcel-1.8.1/Classes/PHPExcel.php';
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle('病例详情列表');

        $objPHPExcel->getActiveSheet()->mergeCells('A1:A2');
        $objPHPExcel->getActiveSheet()->setCellValue('B1','基础信息');
        $objPHPExcel->getActiveSheet()->mergeCells('B1:R2');
        $objPHPExcel->getActiveSheet()->getStyle('B1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        $objPHPExcel->getActiveSheet()->setCellValue('S1','检查信息');
        $objPHPExcel->getActiveSheet()->mergeCells('S1:AR1');
        $objPHPExcel->getActiveSheet()->getStyle('S1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        $objPHPExcel->getActiveSheet()->setCellValue('U2','右眼信息');
        $objPHPExcel->getActiveSheet()->mergeCells('U2:AF2');
        $objPHPExcel->getActiveSheet()->getStyle('U2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        $objPHPExcel->getActiveSheet()->setCellValue('AG2','左眼信息');
        $objPHPExcel->getActiveSheet()->mergeCells('AG2:AR2');
        $objPHPExcel->getActiveSheet()->getStyle('AG2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        for($i=0;$i<count($fieldlist);$i++){

                $objPHPExcel->getActiveSheet()->setCellValue($caselist[$i] . 3, $fieldlist[$i]);
                //设置单元格居中（影响速度不设了）
                $objPHPExcel->getActiveSheet()->getStyle($caselist[$i] . 3)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

                //设置单元格宽度
                $objPHPExcel->getActiveSheet()->getColumnDimension($caselist[$i])->setWidth($sheetWidth[$caselist[$i]]);


        }




        for ($i = 4; $i <= count($excelList)+3; $i++) {
            $templist = array();
            foreach($field_list as $field){
                $templist[]=$excelList[$i-4][$field];
            }
            for($j=0;$j<count($templist);$j++){
/*                if($j==18){
                    $objPHPExcel->getActiveSheet()->setCellValue($caselist[$j] . $i, $templist[$j]);
                    $objPHPExcel->getActiveSheet()->getCell($caselist[$j] . $i)->getHyperlink()->setUrl($templist[$j]);
                    $objPHPExcel->getActiveSheet()->getCell($caselist[$j] . $i)->getHyperlink()->setTooltip('Navigate to website');
                    $objPHPExcel->getActiveSheet()->getStyle($caselist[$j] . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);

                }else{*/
                    $objPHPExcel->getActiveSheet()->setCellValue($caselist[$j] . $i, $templist[$j]);
                    //设置单元格居中（影响速度不设了）
                    $objPHPExcel->getActiveSheet()->getStyle($caselist[$j] . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
               // }
            }
        }

        //合拼单元格
        if($recordIdsCell){
            foreach($recordIdsCell as $v){
                $vcount = count($v);
                for($i="B";$i<="R";$i++){
                    $objPHPExcel->getActiveSheet()->mergeCells($i.($v[0]+4).":".$i.($v[$vcount-1]+4));
                    $objPHPExcel->getActiveSheet()->getStyle($i.($v[0]+4))->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                }
            }
        }



        //$objPHPExcel->getActiveSheet()->mergeCells('B4:B7');
        //$objPHPExcel->getActiveSheet()->getStyle('B4:B7')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);

        header('Content-Disposition: attachment; filename=detail.xlsx');
        \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007')->save("php://output");

    }






    public function info(){
        $id = I('id');
        $row = RecordModel::singleton()->getOne($id);
        $list = RecordModel::singleton()->getRecordDetailList($id);
        $row['eyelid_status']=implode(',',array_values(unserialize($row['eyelid_status'])));
        $row['past_history']=implode(',',array_values(unserialize($row['past_history'])));

        $this->assign('info', $row);
        $this->assign('_list',$list);
        $this->display();
    }


   public function detail(){
       $id = I('id');
       $detail = RecordModel::singleton()->getRecordDetail($id);
       $this->assign('info', $detail);
       $this->display();
   }

    /**
     * 病历删除
     * @author xu
     */
    public function deltet(){
        $id = array_unique((array)I('id',0));
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        if(RecordModel::singleton()->delete($id)!==false){
            $this->success('操作成功');
        }else{
            $this->error('数据库出错');
        };

    }

    /**
     * 病历显示
     * @author xu
     */
    public function show(){
        $id = array_unique((array)I('id',0));
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        if(RecordModel::singleton()->show($id)!==false){
            $this->success('操作成功');
        }else{
            $this->error('数据库出错');
        };

    }
    /**
     * 病历隐藏
     * @author xu
     */
    public function hide(){
        $id = array_unique((array)I('id',0));
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        if(RecordModel::singleton()->hide($id)!==false){
            $this->success('操作成功');
        }else{
            $this->error('数据库出错');
        };

    }

    /**
     * 评论列表
     * @author xu
     */
    public function commentList(){
        $record_id = I('record_id');
        $list = CommentModel::singleton()->getList($record_id);
        $this->assign('record_id',$record_id);
        $this->assign('_list',$list);
        $this->display('Comment/list');
    }


    /**
     * 添加评论视图
     * @author huajie <banhuajie@163.com>
     */
    public function addComment(){
        $record_id = I('record_id');
        $this->assign('record_id',$record_id);
        $this->display('Comment/edit');
    }


    /**
     * 编辑评论视图
     * @author huajie <banhuajie@163.com>
     */
    public function editComment(){
        $record_id = I('record_id');
        $this->assign('record_id',$record_id);
        $id = I('get.id');
        empty($id) && $this->error('参数不能为空！');
        $data = D('Comment')->field(true)->find($id);
        $this->assign('data',$data);
        $this->display('Comment/edit');
    }

    /**
     * 编辑评论
     * @author huajie <banhuajie@163.com>
     */
    public function saveComment(){
        $record_id = I('record_id');
        $res = D('Comment')->update();
        if(!$res){
            $this->error(D('Comment')->getError());
        }else{
            $this->success($res['id']?'更新成功！':'新增成功！', U('Record/commentList',['record_id'=>$record_id]));
        }
    }

    /**
     * 删除评论
     * @author xu
     */
    public function deltetComment(){
        $record_id = I('record_id');
        $id = array_unique((array)I('id',0));
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['id'] =   array('in',$id);
        if ( false !== CommentModel::singleton()->del($map,$record_id) ){
            $this->success('删除成功',U('Record/commentList',['record_id'=>$record_id]),1);
        }else{
            $this->error('删除失败！');
        }

    }
    /**
     * 新评论列表
     * @author xu
     */
    public function newCommentList(){
        $record_id = I('record_id');
        $is_show_name_arr =array('0'=>"不匿名","1"=>"匿名");
        $list = MedicalCommentModel::singleton()->getList($record_id);

        //user_id_list
        $userIds = array_column($list,'user_id');
        $nameList =[];
        if(!empty($userIds)){
            $where['id'] =array('in',$userIds);
            $userList = UserModel::singleton()->where($where)->select();
            $nameList = array_column($userList,'name','id');
        }

        foreach ($list as $key=>$value){
            $list[$key]['is_show_name_text']=$is_show_name_arr[$value['is_show_name']];
            $list[$key]['username'] = isset($nameList[$value['user_id']]) ? $nameList[$value['user_id']] : '';
        }
        $this->assign('record_id',$record_id);
        $this->assign('_list',$list);
        $this->display('Record/list');
    }
    /**
     * 评论置顶
     * @author xu
     */
    public function top(){
        $id = array_unique((array)I('id',0));
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        if(MedicalCommentModel::singleton()->top($id)!==false){
            $this->success('操作成功');
        }else{
            $this->error('数据库出错');
        };
    }
    /**
     * 取消置顶
     * @author xu
     */
    public function low(){
        $id = array_unique((array)I('id',0));
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        if(MedicalCommentModel::singleton()->low($id)!==false){
            $this->success('操作成功');
        }else{
            $this->error('数据库出错');
        };
    }

    /**
     * 删除评论
     * @author xu
     */
    public function deltetNewComment(){
        $record_id = I('record_id');
        $id = array_unique((array)I('id',0));
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['id'] =   array('in',$id);
        if ( false !== MedicalCommentModel::singleton()->del($map,$record_id) ){
            $this->success('删除成功',U('Record/newCommentList',['record_id'=>$record_id]),1);
        }else{
            $this->error('删除失败！');
        }

    }

    /**
     * 获取生成的二维码
     * @date 2022-03-23 17:06
     */
    public function getQrcodeUrl(){
        //需要生成的小程序码ID
        $record_id = $_GET['id'];
        //$qr_code_url ="https://projectapi.wan888888.com/dmk_bj/Upload/2022-03-23/1648024863_3087.jpg";
        try{
            $result = (new WeChatService())->getMiniQrCode($record_id);
            if ($result['status'] == 0){
                Log::record("{$record_id} : " . $result['info']);
                throw new \Exception('获取小程序码失败'.json_encode($result));
            }
            $qr_code_url = ConfigUtils::getConfig('SERVER_URL') . $result['info'];
            MedicalRecordModel::singleton()->updateData($record_id, ['qr_code_url' => $qr_code_url]);
            $this->formatjson(['qr_code_url'=>$qr_code_url,'code'=>0]);
        }catch (\Exception $e){
            Log::record("{$record_id} : " . $e->getMessage());
            $this->formatjson(['msg'=>'获取小程序码失败','code'=>-1]);
        }

    }
    public function formatjson($data=array()){
        header ("Content-Type:application/json; charset=utf-8;");
        echo json_encode($data);
        exit();
    }
}
